<?php

use Illuminate\Database\Capsule\Manager as DB;

class Store_ApplyController extends CommonController
{
    public function applyAction()
    {
        $params = $this->getPost();
        try {
            Validate::check($params, [
                'name' => ['role' => 'required', 'msg' => '店铺名称'],
                'realname' => ['role' => 'required', 'msg' => '联系人'],
                'phone' => ['role' => 'required', 'func'=>'isPhone', 'msg' => '手机号'],
                'area_id' => ['role' => 'required', 'msg' => '所在区域'],
                'address' => ['role' => 'required', 'msg' => '详细地址'],
                'openhours' => ['role' => 'required', 'msg' => '营业时间'],
                'openweeks' => ['role' => 'required', 'msg' => '营业日'],
            ]);
        } catch (Exception $e) {
            json(['code' => 0, 'msg' => $e->getMessage()]);
            exit();
        }
        $user = \app\service\auth::getUser();

        $area = areaModel::find($params['area_id']);
        $city = areaModel::find($area->pid);
        $province = areaModel::find($city->pid);

        // 查询审核未通过的或者驳回的门店申请信息
        $apply = \app\modules\Admin\models\storeapplyModel::where('member_id', $user->id)
            ->whereIn('status', [-1, 0])
            ->first() ?: new \app\modules\Admin\models\storeapplyModel();

        $apply->member_id = $user->id;
        $apply->name = $params['name'];
        $apply->images = implode(';', $params['images']);
        $apply->realname = $params['realname'];
        $apply->phone = $params['phone'];
        $apply->province_name = $province->name;
        $apply->city_name = $city->name;
        $apply->area_name = $area->name;
        $apply->province_id = $province->id;
        $apply->city_id = $city->id;
        $apply->area_id = $area->id;
        $apply->address = $params['address'];
        $apply->latitude = $params['latitude'] ?: null;
        $apply->longitude = $params['longitude'] ?: null;
        $apply->openhours = $params['openhours'];
        $apply->openweeks = $params['openweeks'];
        $apply->status = 0;
        $apply->apply_num = ($apply->apply_num ?? 0) + 1;
        $apply->save();

        json(['code' => 1, 'msg' => '门店申请提交成功', 'data' => $apply]);
    }

    public function infoAction()
    {
        $user = \app\service\auth::getUser();
        $apply = \app\modules\Admin\models\storeapplyModel::where('member_id', $user->id)
            ->whereIn('status', [-1, 0])
            ->first();
        json(['code' => 1, 'msg' => '', 'data' => $apply]);
    }
}
